#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
//#include <6502.h>
#include <peekpoke.h>
#include <conio.h>

#include "Buffers.h"
#include "Loader.h"
#include "CopyFiles.h"

#pragma code-name("LOADER");
#pragma rodata-name("LOADER");
//#pragma data-name("LOADER");

extern const unsigned int _EAPI_LOAD__;

unsigned long eapi_load(char *filename)
{
	int i = 0, r = 0;
	unsigned int offset = 0xA000, length = 0, end = (unsigned int)&_EAPI_LOAD__;
	unsigned int bytes = 0;
	easyfsfile_t *fileptr;
	//struct regs *regs;
	//char fname[17];

	// set bank to 0 so that the EasyFS records are in at $A000
	asm ("lda #$00");
	asm ("jsr $df86");
	asm ("jsr $df89");

	for(i = 0; i < strlen(filename); ++i)
	{
		buffer1[i] = tolower(filename[i]);
	}

	buffer1[i] = '\0';

	for(; offset < end; offset += sizeof(easyfsfile_t))
	{
		fileptr = (easyfsfile_t*)offset;

		if(fileptr->flags == 0xFF) break;

		for(i = 0; i < strlen(filename); ++i)
		{
			if(fileptr->filename[i] >= 0x61 &&
				fileptr->filename[i] <= 0x7a)
			{
				buffer2[i] = fileptr->filename[i] - 0x20;
			}
			else
			{
				buffer2[i] = fileptr->filename[i];
			}
		}

		buffer2[i] = '\0';

		if(strcmp(buffer1, buffer2) == 0)
		{
			//printf("\n%d, %02X%02X", fileptr->bank, fileptr->size_middle, fileptr->size_lsb);
			//cgetc();
			r = copyFile(fileptr->bank, fileptr->size_middle, fileptr->size_lsb);
			//printf("\nAfter copyFile(...) : r=%d", r); cgetc();
		}
	}

	return r;
}

